package com.javasm.mb_store_api_final.adminLogin.login.admin;

import com.alibaba.fastjson2.JSONObject;
import com.javasm.utils.RequestBodyUtil;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Author: xmm
 * <p>
 * &#064;@Description:
 * <p>
 * &#064;@Date 2024/7/31 下午3:08
 */
public class AdminLoginFilter extends AbstractAuthenticationProcessingFilter {

    public AdminLoginFilter() {
        //当前的登录方式,url地址和请求类型
        super(new AntPathRequestMatcher("/user_login", "POST"));
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        //如果不是post方法请求,报错
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //判断 获取的参数 是不是 json数据
        if (!request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            throw new AuthenticationServiceException("请求类型不是JSON: " + request.getContentType());
        }
        //把用户传入的json字符串 获取到
        String json = RequestBodyUtil.read(request);
        Map<String, String> map = JSONObject.parseObject(json, Map.class);
        //接收参数
        String username = map.get("username");
        String password = map.get("password");
        username = username == null ? "" : username.trim();
        password = password == null ? "" : password.trim();
        //手机号验证码 封到一个token对象中
        AdminAuthenticationToken token = new AdminAuthenticationToken(username,password);
        //补充详情
        setDetails(request,token);

        return this.getAuthenticationManager().authenticate(token);
    }
    protected void setDetails(HttpServletRequest request, AdminAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}
